/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import core.DriverManager;
import core.MediaManager;
import core.ScreenEngine;
import datamodel.Order;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import network.Connection;
import network.PacketBuilder;
import view.additional.CellItem;
import view.additional.ThumbList;
import view.additional.TickerRenderer;
import view.commands.CenterCommand;

/**
 *
 * @author kvest
 */
public class NewOrderForm extends Form 
{
    private static final long SHOW_ORDER_TIMEOUT = 30000L;
    private static final int REFUSE_COMMAND_ID = 0;
    private static final int TIME_COMMAND_ID = 1;
    private static final int BACK_COMMAND_ID = 2;
    private static final int GET_COMMAND_ID = 3;

    private TextArea orderText;
    private Command refuseCommand;
    private Command timeCommand;
    private CenterCommand centerCommand;
    
    private ThumbList times;
    private Command backCommand;
    private Command getCommand;
    
    private Vector orders;
    private Order shownOrder;
    private long startShowTime;
    
    private String titleName;
    private int titleColor;
    private int titleFontColor;
    private int defaultTitleColor;
    private int defaultTitleFontColor;
   
    public NewOrderForm(String titleName, int titleColor, int titleFontColor) {
        this(titleName);
        
        this.titleColor = titleColor;
        this.titleFontColor = titleFontColor;
        getTitleComponent().getStyle().setBgColor(titleColor);
        getTitleComponent().getStyle().setFgColor(titleFontColor);
    }
    
    public NewOrderForm(String titleName)
    {
        super(titleName);
        this.titleName = titleName;

        orders = new Vector();
        shownOrder = null;
        defaultTitleColor = getTitleComponent().getStyle().getBgColor();
        defaultTitleFontColor = getTitleComponent().getStyle().getFgColor();
        titleColor = defaultTitleColor;
        titleFontColor = defaultTitleFontColor;
        
        init();
        
        startTimer();
    }
    
    private void init()
    {
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setCyclicFocus(false);

        //Текст заказа
        orderText = new TextArea("", 1, 30);
        orderText.setEditable(false);
        orderText.setGrowByContent(true);

        //Команды
        refuseCommand = new Command("back", REFUSE_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                //Отказываемся от заказа
                refuseShownOrder();

                evt.consume();
            }
        };

        timeCommand = new Command("time", TIME_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                //Останавливаем мелодию
                MediaManager.getManager().stopMusic();
            
               //Показываем выбор времени
               setTimeComponents();

               evt.consume();
            }
        };
        
        centerCommand = new CenterCommand(timeCommand);
        
        times = new ThumbList();
        times.setSelectCommandText("...");
        times.setFixedSelection(ThumbList.FIXED_NONE_CYCLIC);
        TickerRenderer render = new TickerRenderer();
        times.setRenderer(render);
        
        String min = (new Label("min")).getText();
        times.addItem(new CellItem(5, "5 " + min));
        times.addItem(new CellItem(10, "10 " + min));
        times.addItem(new CellItem(15, "15 " + min));
        times.addItem(new CellItem(20, "20 " + min));
        times.addItem(new CellItem(30, "30 " + min));
        times.addItem(new CellItem(45, "45 " + min));
        times.addItem(new CellItem(60, "60 " + min));
        
        backCommand = new Command("back", BACK_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
               //Показываем сам заказ
               setOrderComponents();

               evt.consume();
            }
        };
                
        getCommand = new Command("select", GET_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                CellItem selected = (CellItem)times.getSelectedItem();
                if (selected != null)
                {
                    //Берем заказ
                    getOrder(selected.getId());
                }

               evt.consume();
            }
        };
        
        times.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt) 
            {
                getCommand.actionPerformed(evt);
            }
        });
    }
 
    private void startTimer()
    {
        TimerTask task = new TimerTask()
        {
            public void run()
            {
//System.out.println("timer");                
                if (!isVisible())
                {
//System.out.println("not visible");                     
                    return;
                }
                
                if ((System.currentTimeMillis() - startShowTime) > SHOW_ORDER_TIMEOUT)
                {
//System.out.println("timer refuse");                     
                    //Типо отказываемся от заказа
                    refuseShownOrder();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 20000, 5000);
    }
    
    public void show()
    {
        setContent();
        
        super.show();
    }
    
    private synchronized void refuseShownOrder()
    {
        //Отправляем запрос нажатия "Назад"
        byte[] data = PacketBuilder.createOrderRefuseRequest(DriverManager.getManager().getDriverID(), (shownOrder == null ? 0 : shownOrder.getId()));
        Connection.getConnection().send(data);
                
        boolean noOrders = true;
        synchronized(orders)
        {
            noOrders = orders.isEmpty();
        }
        
        //Если заказов уже нет
        if (noOrders)
        {
            //Останавливаем мелодию
            MediaManager.getManager().stopMusic();
            
            shownOrder = null;
            
            //Закрываем форму
            if (ScreenEngine.getEngine().getCurrent() == this)
            {
                ScreenEngine.getEngine().pop(true);
            }
        }
        else
        {
            //Иначе - отображаем следующий заказ
            setContent();
        }
    }
    
    private void setOrderComponents()
    {
        removeAll();
        removeAllCommands();
        
        setTitle(titleName);
        getTitleComponent().getStyle().setBgColor(titleColor);
        getTitleComponent().getStyle().setFgColor(titleFontColor);
        
        addComponent(orderText);
        
        if (!Display.getInstance().isTouchScreenDevice())
        {
            addCommand(centerCommand);
        }    
        addCommand(timeCommand);
        addCommand(refuseCommand);

        repaint();
    }
    
    private void setTimeComponents()
    {
        removeAll();
        removeAllCommands();
        
        setTitle("time");
        getTitleComponent().getStyle().setBgColor(defaultTitleColor);
        getTitleComponent().getStyle().setFgColor(defaultTitleFontColor);
        
        addComponent(times);
        setFocused(times);
        
        addCommand(getCommand);
        addCommand(backCommand);

        repaint();
    }
    
    private synchronized void setContent()
    {
//        shownOrder = null;
        synchronized(orders)
        {
            if (orders.size() > 0)
            {
                shownOrder = (Order)orders.elementAt(0);
                orders.removeElementAt(0);
            }
        }
        
        if (shownOrder != null)
        {
            orderText.setText(shownOrder.getFullText());
            startShowTime = System.currentTimeMillis();
        }
        else
        {
            orderText.setText("");
            startShowTime = 0;
        }

        setOrderComponents();
    }
    
    public void addOrder(Order order)
    {
        synchronized(orders)
        {
            orders.addElement(order);
        }
    }
    
    private void getOrder(int time)
    {
        //Удаляем все заказы
        synchronized(orders)
        {
            orders.removeAllElements();
        }
        
        if (shownOrder != null)
        {
            //Удаляем форму заказа
            ScreenEngine.getEngine().pop(false);

            //Отображаем форму прогресса
            ScreenEngine.getEngine().push(new ProgressForm());

            //Формируем запрос
            byte[] data = PacketBuilder.createGetOrderRequest(DriverManager.getManager().getDriverID(), shownOrder.getId(), time);

            //Отправляем запрос
            boolean sendSuccess = Connection.getConnection().send(data);
            
            shownOrder = null;
        }
            
        //Возвращаемся на предыдущую форму
        ScreenEngine.getEngine().pop(true);
    }
}
